const busDB = require('../util/busDB'),
  log = require('../util/log'),
  SQL_FIELDS = ['id', 'name'];

exports.select = (obj, resolve) => {
  resolve = resolve || (() => {
  });
  var sql = 'select * from service where 1=1',
    paras = [];
  for (var key in obj) {
    if (SQL_FIELDS.indexOf(key) != -1) {
      sql += ' and ' + key + '=?';
      paras.push(obj[key])
    }
  }
  busDB.query(sql, paras, (err, rows, fields) => {
    if (err) {
      log(err)
      resolve([])
      return
    }
    rows.forEach(row => {
      exports.fillProp(row)
    })
    resolve(rows)
  })
}

exports.fillProp = service => {
  service.getUrls = function (resolve, reject) {
    if (!!this.urls) {
      resolve(this.urls);
      return
    }
    require('./bus/urlDao').select({
      service: this.id
    }, urls => {
      this.urls = urls
      resolve(this.urls)
    }, err => {
      reject(err)
    })
  }
}
